package com.rujue.qianzhi.config;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import javax.annotation.PostConstruct;

import org.I0Itec.zkclient.ZkClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

@Configuration
public class ZooKeeperConfig {
	private static final Logger logger = LoggerFactory.getLogger(ZooKeeperConfig.class);

	@Value("${zookeeper.basePath}")
	String basePath;

	@Value("${zookeeper.serverlist}")
	String serverList;
	
	@Value("${zookeeper.seconds}")
	int seconds;

	@Value("${thrift.port}")
	String port;
	
	

	ExecutorService executor = Executors.newSingleThreadExecutor();

	// 向Zookeeper注册本服务
	public ZkClient registService(ZkClient zkClient) {

		if( zkClient == null ){
			zkClient = new ZkClient(serverList);
			logger.info("创建zookeeper会话: "+serverList);
		}else{
			logger.info("zookeeper会话已存在: "+serverList);
		}

		boolean rootExists = zkClient.exists(basePath);
		if (!rootExists) { // 递归创建永久节点
			zkClient.createPersistent(basePath,true);
			logger.info("递归创建节点: "+basePath);
		}else{
			logger.info("已存在节点: "+basePath);
		}

		String ip = null;
		try {
			ip = InetAddress.getLocalHost().getHostAddress().toString();
		} catch (UnknownHostException e) {
			logger.error("获取本机地址失败",e);
		}
		logger.info("本机IP: "+ip);
		
		String serviceInstance = ip + ":" + port;
		String path = basePath + "/" + serviceInstance;

		// 在zookeeper创建一个临时节点
		rootExists = zkClient.exists(path);
		if (!rootExists) {
			zkClient.createEphemeral(path);
			logger.info("创建临时节点: "+path);
		}else{
			logger.info("临时节点已存在: "+path);
		}
		return zkClient;
	}

	@PostConstruct
	public void init() {
		executor.execute(new Runnable() {
			@Override
			public void run() {
				ZkClient zkClient = null;
				while(true){
					zkClient = registService(zkClient);
					try {
						Thread.sleep(1000 * 60 ); // 60秒检查一次服务是否存在
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			}
		});
	}
}
